package com.lin;

import java.util.HashMap;
import java.util.Map;

public class Solution621 {
    public static void main(String[] args) {
//        leastInterval(new char[]{'A','A','A','B','B','B'},2);
//        leastInterval(new char[]{'A','A','A','B','B','B'},0);
        leastInterval(new char[]{'A','A','A','A','A','A','B','C','D','E','F','G'},2);
    }
    public static int leastInterval(char[] tasks, int n) {
        Map<Character,Integer> map = new HashMap<>();
        Map<Character,Integer> mapTime = new HashMap<>();
        for (char task : tasks) {
            if (map.containsKey(task)){
                Integer integer = map.get(task);
                integer++;
                map.put(task,integer);
            }
            else {
                map.put(task,1);
            }
        }
        for (Character character : map.keySet()) {
            mapTime.put(character,0);
        }

        int currentTime=0;
        for (int i=0;i<tasks.length;i++){
            Integer maxInteger = 0;
            Character currentTask = null;
            while (currentTask == null){
                currentTime++;
                for (Character character : map.keySet()) {
                    if(map.get(character)>maxInteger && ((currentTime-mapTime.get(character)>n)||mapTime.get(character)==0)){
                        currentTask = character;
                        maxInteger = map.get(character);
                    }
                }

            }
            maxInteger--;
            if(maxInteger == 0){
                map.remove(currentTask);
            }else {
                map.put(currentTask,maxInteger);
            }
//            System.out.println(currentTask+":"+currentTime);
            mapTime.put(currentTask,currentTime);
        }
        return currentTime;
    }
}
